package com.yan_jiu_sheng.LeetCodeHot100.AC;

/**
 * https://leetcode.cn/problems/diameter-of-binary-tree/description/?envType=study-plan-v2&envId=top-100-liked
 * 通过
 * 题解：https://leetcode.cn/problems/diameter-of-binary-tree/solutions/139683/er-cha-shu-de-zhi-jing-by-leetcode-solution
 *
 * @author yulongTian
 * @create 2024-06-01 14:53
 */
public class Test40 {
    public static void main(String[] args) {
        TreeNode treeNode1 = new Test40().new TreeNode(1);
        TreeNode treeNode2 = new Test40().new TreeNode(2);
        TreeNode treeNode3 = new Test40().new TreeNode(3);
        TreeNode treeNode4 = new Test40().new TreeNode(4);
        TreeNode treeNode5 = new Test40().new TreeNode(5);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode2.right = treeNode5;
        System.out.println(new Test40().diameterOfBinaryTree(treeNode1));
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private int maxWide = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        preTravel(root);
        return maxWide;
    }


    private void preTravel(TreeNode root) {
        if (root == null) {
            return;
        }
        //左
        preTravel(root.left);
        //根
        int depthLeft = maxDepth(root.left);
        int depthRight = maxDepth(root.right);
        maxWide = Math.max(depthLeft + depthRight, maxWide);
        //右
        preTravel(root.right);
    }

    private int maxHeight = 0;

    private int maxDepth(TreeNode root) {
        maxHeight = 0;
        if (root == null) {
            return 0;
        }
        treeTravel(root, 0);
        return maxHeight;
    }

    private void treeTravel(TreeNode root, int height) {
        if (root == null) {
            if (maxHeight <= height) {
                maxHeight = height;
            }
            return;
        }
        //左
        treeTravel(root.left, height + 1);
        //右
        treeTravel(root.right, height + 1);
    }

}
